﻿using BlazorOrdering.Core;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorOrdering.Application
{
    public class OrderService : IOrderService, ITransient, IDynamicApiController
    {


        private readonly IRepository<Core.Order> _OrderRepository;
        public OrderService(IRepository<Core.Order> orderRepository)
        {
            _OrderRepository = orderRepository;
        }


        /// <summary>
        /// 添加一个订单，成功返回 ok ，不成功返回操作失败的信息
        /// </summary>
        /// <returns></returns>
        public string AddOneOrder(Core.Order order)
        {
            //throw new NotImplementedException();
            var newEntity = _OrderRepository.InsertNow(order);
            if (newEntity != null)
            {
                return "ok";
            }
            else
            {

                return "添加菜谱失败，请联系系统管理员";
            }
        }


        public Task<string> CancelOrdersAsync(Order order)
        {

            string OperatingResults = "";
            try
            {
                //先在退订记录中增加退订
                var corepository = Db.GetRepository<CancellationOrder>();
                CancellationOrder co = new CancellationOrder();
                co.CancellTime = DateTime.Now;
                co.Day = order.Day;
                co.UserName = order.UserName;
                co.Total = order.Total;
                co.HasBreakfast = order.HasBreakfast;
                corepository.InsertNow(co);


                //然后删除订单表中的订单

                var orderinDB = _OrderRepository.Find(order.Id);
                if (orderinDB != null)
                {
                    _OrderRepository.DeleteNow(orderinDB);
                    OperatingResults = "ok";
                }
                else
                {
                    OperatingResults = "数据库中不存在订单，删除订单操作失败！";
                }


            }
            catch (Exception)
            {
                OperatingResults = "操作中遇到了错误，删除订单操作失败！";
                throw;
            }

            return Task.FromResult(OperatingResults);
        }


        /// <summary>
        /// 返回某人可以退订的订单
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public Task<List<Order>> GetOnesCanCancelOrdersAsync(string username)
        {
            using (var dbContext = Db.GetNewDbContext())

            {

                //计算筛选条件
                List<Order> orders = new List<Order>();
                DateTime sday = DateTime.Now;
                int hour = DateTime.Now.Hour;
                if (hour < 23)
                {
                    //23点前可以退明天的（日期大于今天）
                    sday = DateTime.Now.Date;
                    orders = dbContext.Set<Order>().Where(m => m.Day > sday)
                                            .OrderBy(m => m.Day)
                                            .ToList();
                    //9点前，今天不含早餐的也能退（日期等于今天并且不含早餐）
                    if (hour < 9)
                    {
                        var otherOrders = dbContext.Set<Order>().Where(m => m.Day == sday.Date && m.HasBreakfast != true)
                                              .ToList();
                        if (otherOrders.Count > 0)
                        {
                            foreach (var item in otherOrders)
                            {
                                orders.Add(item);
                            }
                        }
                    }
                }
                else
                {
                    //23点以后，只能退后天的（日期大于明天）
                    sday = DateTime.Now.Date.AddDays(1);
                    orders = dbContext.Set<Order>().Where(m => m.Day > sday)
                                            .OrderBy(m => m.Day)
                                            .ToList();
                    //23点以后，明天不含早餐的也能退（日期=明天并且不含早餐）
                    var otherOrders = dbContext.Set<Order>().Where(m => m.Day == sday.Date && m.HasBreakfast != true)
                                            .ToList();
                    if (otherOrders.Count > 0)
                    {
                        foreach (var item in otherOrders)
                        {
                            orders.Add(item);
                        }
                    }
                }
                return Task.FromResult(orders.Adapt<List<Order>>());
            }
        }
    }
}
